package jnpf.message.service.impl.open;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.constant.MsgCode;
import jnpf.constant.PermissionConst;
import jnpf.message.model.message.OpenBaseModel;
import jnpf.message.model.message.OpenDeptModel;
import jnpf.message.model.message.OpenPositionModel;
import jnpf.message.service.SynThirdInfoService;
import jnpf.message.service.ThirdOpenService;
import jnpf.message.util.SynThirdConsts;
import jnpf.permission.entity.*;
import jnpf.permission.service.*;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static jnpf.message.model.message.OpenBaseModel.OperationType.DISABLE;

@Service
@Log4j2
@RequiredArgsConstructor
public class ThirdOpenPositionServiceImpl implements ThirdOpenService {

	private final SynThirdInfoService synThirdInfoService;

	private final UserProvider userProvider;

	private final PositionService positionService;

	private final OrganizeService organizeService;

	private final UserService userService;

	private final UserRelationService userRelationService;

	private final OrganizeRelationService organizeRelationService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Object beforeProcess(OpenBaseModel openBaseModel, Map<String, OpenDeptModel> organizeMap) {
		OpenPositionModel positionModel = (OpenPositionModel) openBaseModel;
		OpenBaseModel.OperationType operationType = positionModel.getType();
		String description = "";
		String positionId = positionModel.getPositionId();
		try {
			switch (operationType) {
				case ADD:
				case EDIT:
				case ENABLE:
				case DISABLE:
					PositionEntity positionEntity = positionService.getInfo(positionId);
					//判定组织是否存在
					if(MapUtil.isNotEmpty(organizeMap)){
						if (!organizeMap.containsKey(positionModel.getDeptId())) {
							description = "组织不存在";
							break;
						}
					}else {
						OrganizeEntity organizeEntity = organizeService.getById(positionModel.getDeptId());
						if(Objects.isNull(organizeEntity)){
							description = "组织不存在";
							break;
						}
					}
					boolean isFilter = false;
					if (Objects.nonNull(positionEntity)) {
						// 当岗位绑定用户不让其更改
						if (userRelationService.existByObj(PermissionConst.POSITION, positionId)) {
							if (!positionService.getInfo(positionId).getOrganizeId().equals(positionModel.getDeptId())) {
								description = MsgCode.FA023.get();
								break;
							}
							if (DISABLE == operationType && positionEntity.getEnabledMark() == 1) {
								description = MsgCode.FA030.get();
								break;
							}
						}
						isFilter = true;
					} else {
						positionEntity = new PositionEntity();
					}
					positionEntity.setEnCode(RandomUtil.getRandomCode());
					positionEntity.setSortCode(0L);
					positionEntity.setFullName(positionModel.getName());
					positionEntity.setEnabledMark(DISABLE == operationType ? 0 : 1);
					positionEntity.setId(positionId);
					positionEntity.setType("2");
					positionEntity.setOrganizeId(positionModel.getDeptId());
					if (positionService.isExistByFullName(positionEntity, isFilter)) {
						description = MsgCode.EXIST001.get();
						break;
					}
					if (positionService.isExistByEnCode(positionEntity, isFilter)) {
						description = MsgCode.EXIST002.get();
						break;
					}
					return positionEntity;
				case DELETE:
					if (userRelationService.existByObj(PermissionConst.POSITION, positionId)) {
						description = MsgCode.FA024.get();
						break;
					}
					PositionEntity entity = positionService.getInfo(positionId);
					if (entity != null) {
						List<UserRelationEntity> userRelList = userRelationService.getListByObjectId(positionId);
						if (userRelList.size() > 0) {
							description = MsgCode.FA024.get();
							break;
						}
						for (UserRelationEntity entity1 : userRelList) {
							UserEntity entity2 = userService.getById(entity1.getUserId());
							if (entity2 != null) {
								String newPositionId = entity2.getPositionId().replace(positionId, "");
								if (entity2.getPositionId().contains(positionId)) {
									if (newPositionId.length() != 0 && newPositionId.substring(0, 1).equals(",")) {
										entity2.setPositionId(newPositionId.substring(1));
									} else if (newPositionId.length() != 0) {
										entity2.setPositionId(newPositionId.replace(",,", ","));
									}
								}
							}
						}
						userRelationService.deleteAllByObjId(positionId);

						// 删除岗位与组织之间的关联数据
						QueryWrapper<OrganizeRelationEntity> query = new QueryWrapper<>();
						query.lambda().eq(OrganizeRelationEntity::getObjectType, PermissionConst.POSITION);
						query.lambda().eq(OrganizeRelationEntity::getObjectId, positionId);
						organizeRelationService.remove(query);
						positionService.delete(entity);
					}
			}
		} catch (Exception e) {
			description = e.getMessage();
			throw e;
		} finally {
			saveSynThirdInfoEntity(operationType, SynThirdConsts.DATA_TYPE_POSITION, positionId, StringUtils.isBlank(description) ? 2 : 1, description, synThirdInfoService, userProvider);
		}
		return null;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void afterProcess(List<Object> result) {
		positionService.saveOrUpdateBatch(result.stream().map(e -> (PositionEntity) e).filter(Objects::nonNull).collect(Collectors.toList()));
	}
}
